package jsu.blogger.mapper;

import jsu.blogger.pojo.UserFolder;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface CollectMapper {

    /**
     * 查询用户是否收藏了某个博客帖子
     *
     * @param userId 用户ID
     * @param postId 帖子ID
     * @return 如果返回值大于0，则表示已收藏，否则没有收藏
     */
    Integer checkIfUserHasCollectedPost(@Param("userId") Long userId, @Param("postId") Long postId);

    UserFolder getDefaultFolderByUserId(@Param("userId") Long userId);
    @Insert("INSERT INTO user_folders (user_id, folder_name, folder_description, visibility, is_default,created_at) " +
            "VALUES (#{userId}, #{folderName}, #{folderDesc}, #{visibility}, #{isDefault},#{lastUpdate})")
    @Options(useGeneratedKeys = true, keyProperty = "folderId") // 使能生成的键并将其设置到 folderId 属性
    void insertUserFolder(UserFolder userFolder); // 直接传递 UserFolder 对象

    // 检查用户是否有权访问该收藏夹
    @Select("SELECT COUNT(*) FROM user_folders WHERE folder_id = #{folderId} AND user_id = #{userId}")
    int checkUserFolder(@Param("folderId") Long folderId, @Param("userId") Long userId);

    // 插入帖子到收藏夹
    @Insert("INSERT INTO folder_posts (folder_id, post_id) " +
            "VALUES (#{folderId}, #{postId})")
    void insertFolderPost(@Param("folderId") Long folderId,
                          @Param("postId") Long postId);

    //删除收藏夹
    @Delete("DELETE FROM folder_posts WHERE folder_id = #{folderId}")
    void deleteAllPostsInFolder(@Param("folderId") Long folderId);

    // 根据收藏夹 ID 和帖子 ID 删除特定的帖子
    @Delete("DELETE FROM folder_posts WHERE folder_id = #{folderId} AND post_id = #{postId}")
    void deletePostFromFolder(@Param("folderId") Long folderId, @Param("postId") Long postId);

    //删除用户的收藏夹中相应的帖子
    @Delete("""
        DELETE FROM folder_posts 
        WHERE post_id = #{postId} 
        AND folder_id IN (SELECT folder_id FROM user_folders WHERE user_id = #{userId})
    """)
    int deletePostFromUserFolders(@Param("userId") Long userId, @Param("postId") Long postId);

    List<UserFolder> getUserFolders(@Param("userId") Long userId,
                                    @Param("limit") int limit,
                                    @Param("offset") int offset);

    @Select("SELECT COUNT(*) > 0 FROM folder_posts WHERE folder_id = #{folderId} AND post_id = #{postId}")
    boolean existsByFolderIdAndPostId(@Param("folderId") Long folderId,@Param("postId") Long postId);

    @Select("SELECT COUNT(*) FROM folder_posts WHERE folder_id = #{folderId}")
    int countPostsByFolderId(Long folderId);
    @Select("SELECT folder_name FROM user_folders WHERE folder_id = #{folderId}")
    String getFolderNameById(Long folderId);

    @Update("UPDATE user_folders SET is_default = null WHERE user_id = #{userId} AND is_default IS NOT NULL")
    void resetDefaultFolder(Long userId);
}
